package com.zzh.tree;

public class No450_deleteNode {
    public static void main(String[] args) {
        No450Solution solution = new No450Solution();
        TreeNode root = new TreeNode(1);
        int key = 1;
        TreeNode treeNode = solution.deleteNode(root, key);
    }
}

class No450Solution {
    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) {
            return null;
        }
        if (root.val == key) {
            //删除
            if (root.left == null && root.right == null) {
                return null;
            } else if (root.left == null) {
                return root.right;
            } else if (root.right == null) {
                return root.left;
            } else {
                TreeNode min = findMin(root.right);//找到右子树最小值
                root.val = min.val;
                root.right = deleteNode(root.right, min.val);
            }

        } else if (key < root.val) {
            root.left = deleteNode(root.left, key);
        } else {
            root.right = deleteNode(root.right, key);
        }
        return root;
    }

    public TreeNode findMin(TreeNode node) {
        //最小值一定在左边
        while (node.left != null) {
            node = node.left;
        }
        return node;
    }
}